//===============================================================================
// Microsoft patterns & practices Enterprise Library Contribution
// Common Core Extensions
//===============================================================================

using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace EntLibContrib.Common
{
  /// <summary>
  /// Utility class for serializing and deserializing objects to and from byte streams
  /// </summary>
	/// <remarks>
	/// This utility has been lifted from the Caching block in order to remove the 
	/// direct dependancy on the caching block. Although this goes against best practise it
	/// enables providers to maintain independence from the other blocks as much as possible.
	/// Hopefully one day the MS patterns team will put this utility into
	/// Microsoft.Practices.EnterpriseLibrary.Common
	/// </remarks>
  public static class SerializationUtility
  {
		#region public Methods
    /// <summary>
    /// Converts an object into an array of bytes. Object must be serializable.
    /// </summary>
    /// <param name="value">Object to serialize. May be null.</param>
    /// <returns>Serialized object, or null if input was null.</returns>
    public static byte[] ToBytes(object value)
    {
      if (value == null)
        return null;

      byte[] inMemoryBytes;
      using (MemoryStream inMemoryData = new MemoryStream())
      {
        new BinaryFormatter().Serialize(inMemoryData, value);
        inMemoryBytes = inMemoryData.ToArray();
      }

      return inMemoryBytes;
    }

    /// <summary>
    /// Converts a byte array into an object. 
    /// </summary>
    /// <param name="serializedObject">Object to deserialize. May be null.</param>
    /// <returns>Deserialized object, or null if input was null.</returns>
    public static object ToObject(byte[] serializedObject)
    {
      if (serializedObject == null)
          return null;

      using (MemoryStream dataInMemory = new MemoryStream(serializedObject))
      {
        return new BinaryFormatter().Deserialize(dataInMemory);
      }
    }
    #endregion
  }
}